package oldtest;

import ai.*;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Vector;

import boardgame.*;

public class TicTacToeTest extends Board{
	
	public int previousPlayer = 1;
	private boolean aiON = false;
	
	TicTacToeTest(){
		super();
	}
	
	TicTacToeTest(TicTacToeTest tttt){
		super(tttt);
		this.previousPlayer = tttt.previousPlayer;		
	}
	
	private void copy(TicTacToeTest tttt){
		super.copy(tttt);
		this.previousPlayer = tttt.previousPlayer;
	}
	
	public void setAI(boolean on){
		aiON = on;
	}
	
	public boolean aiStatus(){
		return aiON;
	}
	
	protected void clearBoard() {
		pieces.clear();
		winner = 0;		
		currentPlayer = 1;
		playerCount = 2;
	}

	public Piece moveByAI(){
		Minimax ai = new Minimax();
		AIGameState comp = new AIGameState(this);
		return (TicTac)(ai.searchBestMove(comp, 3));
	}
	
	protected int placePiece(Piece piece) throws Exception{
		Iterator<Piece> i = pieces.iterator();
		Boolean occupied = false;
		while (i.hasNext()){			
			Piece p = i.next();						
			if (p.getPosition() == piece.getPosition()){
				occupied = true;				
				break;
			}
		}
		System.out.println("end of session");
		if (occupied)
			throw new Exception("Error...unclickable is clickable.");
		pieces.add(piece);
		winner = checkGameEnd();		
		previousPlayer = currentPlayer;
		currentPlayer = currentPlayer%playerCount+1;
		if (pieces.size() == 9)
			currentPlayer = 0;
		if (gameEnd())			
			return winner;					
		return 0;		
	}

	private int checkGameEnd(){				
		boolean[][][] occupied = occupiedCells();						
		for (int p = 0; p < 2; p++){
			for (int j = 0; j < 3; j++){			
				if (occupied[p][0][j]&&occupied[p][1][j]&&occupied[p][2][j])
					return p+1;
				if (occupied[p][j][0]&&occupied[p][j][1]&&occupied[p][j][2])
					return p+1;								
			}
			if (occupied[p][0][0]&&occupied[p][1][1]&&occupied[p][2][2])
				return p+1;
			if (occupied[p][2][0]&&occupied[p][1][1]&&occupied[p][0][2])
				return p+1;
		}
		if (pieces.size() == 9)
			return -1;
		return 0;
	}
	
	protected boolean[][][] occupiedCells(){
		Iterator<Piece> i = pieces.iterator();
		boolean[][][] occupied = new boolean[2][3][3];		
		Arrays.fill(occupied[0][0], false);		
		Arrays.fill(occupied[0][1], false);
		Arrays.fill(occupied[0][2], false);
		Arrays.fill(occupied[1][0], false);		
		Arrays.fill(occupied[1][1], false);
		Arrays.fill(occupied[1][2], false);
		while (i.hasNext()){
			Piece p = i.next();
			int[] pos = p.getPosition();
			int plyr = p.owner();
			occupied[plyr-1][pos[0]][pos[1]] = true;
		}
		return occupied;
	}
}
